package mk.com.it.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class RssParser {
	public static List<RssPost> readXml(InputStream in) throws ParserConfigurationException,
			SAXException, IOException {
		List<RssPost> result = new ArrayList<RssPost>();
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();

		// Parse the earthquake feed.
		Document dom = db.parse(in);
		Element docEle = dom.getDocumentElement();

		// Get a list of each earthquake entry.
		NodeList nl = docEle.getElementsByTagName("item");
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {
				RssPost post = new RssPost();
				// get the post element
				Element entry = (Element) nl.item(i);
				// handle the title
				Element title = (Element) entry.getElementsByTagName("title")
						.item(0);
				String titleString = title.getFirstChild().getNodeValue();
				post.setTitle(titleString);
				// handle the date
				Element when = (Element) entry.getElementsByTagName("pubDate")
						.item(0);
				
				String dt = when.getFirstChild().getNodeValue();
				String[] res = dt.split(" ");
				String pubDate = res[1] + " " + res[2] + " " + res[3];
				post.setPubDate(pubDate);

				// handle the link
				Element link = (Element) entry.getElementsByTagName("link")
						.item(0);
				String linkString = link.getFirstChild().getNodeValue();
				post.setLink(new URL(linkString));
				Element authorElement = (Element) entry.getElementsByTagName("dc:creator")
				.item(0);
				String author = authorElement.getFirstChild().getNodeValue();
				post.setCreator(author);
				
				Element descElement = (Element) entry.getElementsByTagName("description")
				.item(0);
				String desc = descElement.getFirstChild().getNodeValue();
				post.setDescription(desc);
				result.add(post);
			}
		}
		return result;
	}
}
